import pymysql


def get_connection():
    return pymysql.connect(
        host='127.0.0.1',
        user='root',
        password='123456',
        database='python_mysql',
        charset='utf8'
    )

def query_data(sql):
    conn = get_connection()
    try:
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        cursor.execute(sql)
        return cursor.fetchall()
    finally:
        conn.close()

def insert_or_update_data(sql):
    conn = get_connection()
    try:
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        cursor.execute(sql)
        conn.commit()
    finally:
        conn.close()

if __name__ == '__main__':
    sql='select * from user'
    sql_insert = "insert user (name,age,email,sex) values ('agges',38,'agges@yeecall.com','man')"
    insert_or_update_data(sql_insert)
    datas = query_data(sql)
    import pprint
    pprint.pprint(datas)